import axios from 'axios'
import { showToast } from 'vant'
import { getToken, logout } from '@/utils/user.js'

const env = import.meta.env.MODE === 'development' ? 'dev' : 'prod'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

// 创建axios实例对象，添加全局配置
const service = axios.create({
    baseURL: import.meta.env.VITE_ADMIN_BASE_URL,
    timeout: 15000
})

// 请求拦截
service.interceptors.request.use((req) => {
    const headers = req.headers
    const token = getToken()
    if (token) {
        headers.Authorization = `Bearer ${token}`
    }
    return req
})

// 响应拦截
service.interceptors.response.use((res) => {
    const { code, msg } = res.data
    if (code === 200 || code === '200') {
        return res.data
    } else if (code === 401 || code === '401' || code == '100005') {
        // if (getToken()) {
        //     showToast(TOKEN_INVALID)
        // } else {
        //     showToast('登录享受更多优质服务')
        // }
        logout()
        return Promise.reject(TOKEN_INVALID)
    } else {
        showToast(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
}, (error) => {
    showToast(`服务器异常${error.message ? '：' + error.message : ''}`)

    return Promise.reject(error)
})
/**
 * 请求核心函数
 * @param {*} options 请求配置
 */
function request(options) {
    options.method = options.method || 'get'
    let isMock
    if (typeof options.mock != 'undefined') {
        isMock = options.mock
    }
    // service.defaults.baseURL = isMock ? import.meta.env.VITE_MOCK_BASE_URL : import.meta.env.VITE_BASE_URL
    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request
